$(function () {
    var status = $("#content").data("status"),
        dateRangePicker = $('#daterangepicker');

    $(".repayment_" + status).addClass("active");

    var initDateRangePicker = function () {
        var rangePast = {
            '今天': [moment(), moment()],
            '昨天': [moment().subtract('days', 1), moment().subtract('days', 1)],
            '最近7天': [moment().subtract('days', 6), moment()],
            '最近30天': [moment().subtract('days', 29), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上个月': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
        };
        var rangeFuture = {
            '今天': [moment(), moment()],
            '未来7天': [moment(), moment().add('days', 6)],
            '未来30天': [moment(), moment().add('days', 29)],
            '未来60天': [moment(), moment().add('days', 59)],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '下个月': [moment().add('month', 1).startOf('month'), moment().add('month', 1).endOf('month')]
        };

        dateRangePicker.daterangepicker({
            ranges: status === "repayed" ? rangePast : rangeFuture,
            startDate: status === "repayed" ? moment().subtract('days', 29) : moment(),
            endDate: status === "repayed" ? moment() : moment().add('days', 29),
            applyClass: "btn-primary btn-block",
            cancelClass: "btn-block",
            format: "YYYY/MM/DD",
            locale: {
                applyLabel: '确定',
                clearLabel: "取消",
                fromLabel: '开始时间',
                toLabel: '结束时间',
                weekLabel: '周',
                customRangeLabel: '选择范围',
                daysOfWeek: "日_一_二_三_四_五_六".split("_"),
                monthNames: "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),
                firstDay: 0
            },
            opens: "left"
        });


        var formatDate = function (date) {
            return $.format.date(new Date(date), "yyyy/MM/dd");
        };
        // 根据状态设定初始日期
        var defaultDate = status === 'repayed'
            ? formatDate(moment().subtract('days', 29)) + ' - ' + formatDate(moment())
            : formatDate(moment()) + ' - ' + formatDate(moment().add('days', 29));

        dateRangePicker.val(defaultDate);
        $(".daterangepicker .ranges ul li:last").hide();
        $(".daterangepicker .ranges .daterangepicker_start_input").remove();
        $(".daterangepicker .ranges .daterangepicker_end_input").remove();
        $(".daterangepicker .ranges .cancelBtn").remove();
    };

    var initTable = function () {
        var table = $('#repaymentList').DataTable({
            //"processing": true,
            //"serverSide": true,
            //"iDeferLoading": 0,
            "ajax": {
                "url": "repayment/getRepays",
                "data": function (d) {
                    d.status = status;
                    var dateRange = dateRangePicker.val().split(" - ");
                    d.startDate = $.format.date(new Date(dateRange[0]), "yyyy-MM-dd");

                    var endTime = moment(dateRange[1], "YYYY/MM/DD").endOf('day');
                    d.endDate = $.format.date(new Date(endTime), "yyyy-MM-dd");
                },
                "type": "POST"
            },
            "columns": [
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": ''
                },
                {"data": "loanTitle"},
                {"data": "userId"},
                {"data": "repayment"},
                {"data": "period"},
                {"data": "status"},
                {"data": "dueDate"},
                {"data": "repayTime"},
                {"data": "id"},
            ],
            "aoColumnDefs": [{
                    "targets": 0, //详情展开按钮
                    "mRender": function () {
                        return '<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>';
                    }
                }, {
                    "targets": 1, //标题
                    "mRender": function (data, type, row) {
                        return data === ''
                            ? '未填写'
                            : '<a href="loan/detail/' + row.loanId + '">' + data + '</a>';
                    }
                }, {
                    "targets": 2, //借款人
                    "mRender": function (data, type, row) {
                        return data === ''
                            ? '未填写'
                            : '<a href="user/index/' + data + '" target="_blank">' + row.userLoginName + '</a>';
                    }
                }, {
                    "targets": 3, //金额
                    "mRender": function (data, type, row) {
                        return $.number(data.total, 2);
                    }
                }, {
                    "targets": 4, //期数
                    "mRender": function (data, type, row) {
                        return data + '/' + row.totalPeriods;
                    }
                }, {
                    "targets": 5, //状态
                    "mRender": function (data, type, row) {
                        return sysRepayStatus[data];
                    }
                }, {
                    "targets": 6, //截止日期
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(data), "yyyy/MM/dd");
                    }
                }, {
                    "targets": 7, //实际还款时间
                    "searchable": false,
                    "visible": status === "repayed" ? true : false,
                    "mRender": function (data, type, row) {
                        return data === null ? "" : $.format.date(new Date(data), "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 8, //操作
                    "searchable": false,
                    "visible": status === "repayed" ? false : true,
                    "mRender": function (data, type, row) {
                        return sys.render("#operationTemplate", row);
                    }
                }],
            "order": [5, "desc"],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ","
            },
            "iDisplayLength": 10,
            "aLengthMenu": [
                [5, 10, 25, 50, -1],
                [5, 10, 25, 50, "全部"]
            ],
            "sDom": '<"dt-panelmenu clearfix"l<"pull-right"T>r>t<"dt-panelfooter clearfix"ip>',
            "oTableTools": {
                "aButtons": [{
                        "sExtends": "xls",
                        "sButtonText": "导出为Excel"
                    }
                ],
                "sSwfPath": root_path + "/js/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
            }
        });
        /**
         * 详情展开/关闭
         */
        $('#repaymentList tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                // 关闭详情
                $(this).html('<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>');
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // 展开详情
                $(this).html('<span class="glyphicons glyphicons-circle_minus text-info cursor-pointer fs14"></span>');
                var detail = sys.render("#detailTemplate", row.data().repayment);
                row.child(detail).show();
                tr.addClass('shown');
            }
        });
        /**
         * 搜索按钮响应事件
         */
        $('#queryRepayBtn').on('click', function () {
            table.ajax.reload();
        });
        /**
         * 标的还款
         */
        $('#repaymentList').on('click', '.repay_link', function (e) {
            e.stopPropagation();
            e.preventDefault();

            var id = $(this).data("id");

            sys.confirm("确定还款？", function (btn) {
                var $btn = $(btn);
                sys.btnSpin($btn);
                sys.processModal();

                $.post("loan/repay", {
                    id: id
                }, function (res) {
                    alert(res.message);
                    if (res.success) {
                        location.reload();
                    } else {
                        sys.btnStop($btn);
                        sys.closeModal();
                    }
                }).fail(function () {
                    alert("服务器错误");
                    sys.btnStop($btn);
                    sys.closeModal();
                });
            });
        });
        /**
         * 标的垫付
         */
        $('#repaymentList').on('click', '.reimburse_link', function (e) {
            e.stopPropagation();
            e.preventDefault();
            var id = $(this).data("id");

            sys.confirm("确定垫付？", function (btn) {
                var $btn = $(btn);
                sys.btnSpin($btn);
                sys.processModal();

                $.post("loan/reimburse", {
                    id: id
                }, function (res) {
                    alert(res.message);
                    if (res.success) {
                        location.reload();
                    } else {
                        sys.btnStop($btn);
                        sys.closeModal();
                    }
                }).fail(function () {
                    alert("服务器错误");
                    sys.btnStop($btn);
                    sys.closeModal();
                });
            });
        });
    };
    initDateRangePicker();
    initTable();
});


